package com.project.server;

import java.io.*;

/**
 * 封装写入流的响应类
 */
public class Response {
    private OutputStream out;
    public Response(OutputStream out){
        this.out = out;
    }

    /**
     * 发送字符串到客户端
     * @param info 发送的字符串
     */
    public void sendMessage(String info){
        try {
            out.write(info.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送文件数据到客户端
     * @param filePath 文件路径
     */
    public void sendFile(String filePath){
        if(filePath == null){
            return ;
        }

        File f = new File(filePath);
        if(f.exists() == false){//如果文件不存在则跳出方法
            return;
        }

        InputStream in = null;
        try {
            in = new FileInputStream(filePath);

            byte[] byteArray = new byte[1024];
            //记录每次读取的字节数
            int len = 0;

            //每次读取1024字节到字节数组，返回当前读取的字节数，返回-1表示读取完毕
            while( (len = in.read(byteArray)) != -1){
                out.write(byteArray,0,len);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
